package com.xzt.security.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xzt.security.config.JwtTokenProvider;
import com.xzt.security.dto.*;
import com.xzt.security.entity.Role;
import com.xzt.security.entity.User;
import com.xzt.security.mapper.RoleMapper;
import com.xzt.security.mapper.UserMapper;
import com.xzt.security.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import com.xzt.security.entity.User;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {

    @Autowired
    private JwtTokenProvider jwtTokenProvider;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Override
    public RegisterResponse register(RegisterRequest request) {
        String username = request.getUsername();
        String rawPassword = request.getPassword();

        // 1. 检查用户名是否已存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        if (userMapper.exists(queryWrapper)) {
            return new RegisterResponse("用户名已存在", null, null);
        }

        // 2. 加密密码
        String encodedPassword = passwordEncoder.encode(rawPassword);

        // 3. 构建用户对象并保存
        User user = new User();
        user.setUsername(username);
        user.setPassword(encodedPassword);

        userMapper.insert(user);

        // 4. 返回结果
        return new RegisterResponse("注册成功", user.getId(), user.getUsername());
    }

    @Override
    public LoginResponse login(LoginRequest request) {
        String username = request.getUsername();
        String rawPassword = request.getPassword();

        // 1. 根据用户名从数据库查询用户
        var userQuery = new QueryWrapper<User>();
        userQuery.eq("username", username);
        User user = userMapper.selectOne(userQuery);

        // 2. 判断用户是否存在
        if (user == null) {
            return new LoginResponse("用户名不存在", null, "fail", null, null);
        }

        // 3. 校验密码（数据库中的 password 是加密的）
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        boolean isPasswordValid = encoder.matches(rawPassword, user.getPassword());

        if (!isPasswordValid) {
            return new LoginResponse("密码错误", null, "fail", null, null);
        }

        // 4. 登录成功，生成 JWT（这里先模拟，后面会用真正的 JWT 工具类生成）
        // 注意：为了简化，这里先返回模拟值，下面我们会实现真正的 JWT 工具和 Security 配置
//        String token = "mock-jwt-token-for-" + username;
        String token = jwtTokenProvider.generateToken(user.getUsername());

        return new LoginResponse(
                "登录成功",
                token, // 后续替换为真实 JWT
                "success",
                user.getUsername(),
                "ROLE_USER"
        );
    }

    @Override
    public UserInfoResponse getCurrentUserInfo() {
        // 从 Spring Security 上下文中获取当前认证用户
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        if (authentication == null || !authentication.isAuthenticated()) {
            throw new RuntimeException("未登录或认证失败");
        }

        // 获取当前用户名
        String username = authentication.getName(); // 已自动从 JWT 中解析

        // 目前简单返回示例数据（你可以后续从数据库查询真实角色）
//        String role = "ROLE_USER"; // 或从数据库/用户详情中获取
        String role = String.valueOf(roleMapper.selectOne(new LambdaQueryWrapper<Role>()
                .select(Role::getRolename)
                .eq(Role::getId,2)));

        return new UserInfoResponse(username, role);
    }

    @Override
    public UserInfoResponse getAdminUserInfo() {
        // 从 Spring Security 上下文中获取当前认证用户
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        if (authentication == null || !authentication.isAuthenticated()) {
            throw new RuntimeException("未登录或认证失败");
        }

        // 获取当前用户名
        String username = authentication.getName(); // 已自动从 JWT 中解析

        // 目前简单返回示例数据（你可以后续从数据库查询真实角色）
//        String role = "ROLE_USER"; // 或从数据库/用户详情中获取
        String role = String.valueOf(roleMapper.selectOne(new LambdaQueryWrapper<Role>()
                .select(Role::getRolename)
                .eq(Role::getId,2)));

        return new UserInfoResponse(username, role);
    }
}